package {
	import as3isolib.display.IsoView;
	import as3isolib.display.scene.IsoGrid;
	import as3isolib.display.scene.IsoScene;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;

	public class Main extends Sprite {

		private var _world:IsoView;
		private var _grid:IsoGrid;
		private var _groupScene:IsoScene;
		private var _group:Group;
		private var _b0:Sprite;
		private var _b1:Sprite;

		//group map
		private var _map:Array = [[0, 'A', 'B', 'C'], ['D', 'E', 'F', 'G']];

		public function Main():void {
			if (stage)
				init();
			else
				addEventListener(Event.ADDED_TO_STAGE, init);
		}

		private function init(e:Event = null):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);
			createWorld();
			createGroup();

			_b0 = createButton("-90", onButtonClick, 10);
			_b1 = createButton("+90", onButtonClick, 60);
		}

		private function onButtonClick(e:MouseEvent):void {
			if (e.target == _b0) {
				_group.rotate(false);
			} else {
				_group.rotate();
			}
		}

		private function createGroup():void {
			_group = new GroupWithPivot(_grid) // new Group(_grid);
			_group.setMap(_map);
			_group.moveTo(60, 60, 0);
			_groupScene.addChild(_group);

		}

		private function createWorld():void {
			_world = new IsoView();
			_world.setSize(400, 400);
			addChild(_world);

			///////// GRID
			_grid = new IsoGrid();
			_grid.setGridSize(10, 10);
			_grid.cellSize = 20;

			var gridScene:IsoScene = new IsoScene();
			gridScene.addChild(_grid);

			_world.addScene(gridScene);

			///////// GROUP SCENE
			_groupScene = new IsoScene();
			_world.addScene(_groupScene);

			_world.addEventListener(Event.ENTER_FRAME, render);
		}

		private function render(e:Event):void {
			_world.render(true);

		}

		private function createButton(label:String, listener:Function, x:Number):Sprite {
			var b:Sprite = new Sprite();
			b.addEventListener(MouseEvent.CLICK, listener);
			b.mouseChildren = false;
			b.graphics.beginFill(0);
			b.graphics.drawRect(0, 0, 40, 30);
			b.graphics.endFill();

			var lbl:TextField = new TextField();
			lbl.textColor = 0xFFFFFF;
			lbl.text = label;

			b.addChild(lbl);
			b.x = x;

			addChild(b);
			return b;

		}
	}
}